<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>我来学Kotlin-起步之习惯用法 - (power up)</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="Kevin Jiang" /><meta name="description" content="数据类 1 data class Customer(val name: String, val email: String) Customer提供了以下方法： getters，如果成员变量使用var定义那么还默认提供setters equals() hashCode() toString() copy() component1(), component2() &amp;hellip;" /><meta name="keywords" content="KevinJiang, AI大模型, AI落地, 全栈工程师, Java, Spring Boot" />






<meta name="generator" content="Hugo 0.84.4 with theme even" />


<link rel="canonical" href="http://kevinjiang.info/post/kotlin/%E6%88%91%E6%9D%A5%E5%AD%A6kotlin-%E8%B5%B7%E6%AD%A5%E4%B9%8B%E4%B9%A0%E6%83%AF%E7%94%A8%E6%B3%95/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">



<link href="/sass/main.min.78f8f17bab244b9ee62ad16480c9584d5fc2db06ae20681d1ca225cefd80767c.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="我来学Kotlin-起步之习惯用法" />
<meta property="og:description" content="数据类 1 data class Customer(val name: String, val email: String) Customer提供了以下方法： getters，如果成员变量使用var定义那么还默认提供setters equals() hashCode() toString() copy() component1(), component2() &hellip;" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://kevinjiang.info/post/kotlin/%E6%88%91%E6%9D%A5%E5%AD%A6kotlin-%E8%B5%B7%E6%AD%A5%E4%B9%8B%E4%B9%A0%E6%83%AF%E7%94%A8%E6%B3%95/" /><meta property="article:section" content="post" />
<meta property="article:published_time" content="2017-06-13T16:44:02+00:00" />
<meta property="article:modified_time" content="2017-06-13T16:44:02+00:00" />

<meta itemprop="name" content="我来学Kotlin-起步之习惯用法">
<meta itemprop="description" content="数据类 1 data class Customer(val name: String, val email: String) Customer提供了以下方法： getters，如果成员变量使用var定义那么还默认提供setters equals() hashCode() toString() copy() component1(), component2() &hellip;"><meta itemprop="datePublished" content="2017-06-13T16:44:02+00:00" />
<meta itemprop="dateModified" content="2017-06-13T16:44:02+00:00" />
<meta itemprop="wordCount" content="1426">
<meta itemprop="keywords" content="Kotlin,Kotlin教程," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="我来学Kotlin-起步之习惯用法"/>
<meta name="twitter:description" content="数据类 1 data class Customer(val name: String, val email: String) Customer提供了以下方法： getters，如果成员变量使用var定义那么还默认提供setters equals() hashCode() toString() copy() component1(), component2() &hellip;"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">(Power up)</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">首页</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">归档</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">标签</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">分类</li>
      </a><a href="/resume/">
        <li class="mobile-menu-item">简历</li>
      </a>
  </ul>

  


</nav>

  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">(Power up)</a>
</div>





<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">首页</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">归档</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">标签</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">分类</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/resume/">简历</a>
      </li>
  </ul>
</nav>

    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">我来学Kotlin-起步之习惯用法</h1>

      <div class="post-meta">
        <span class="post-time"> 2017-06-13 </span>
        <div class="post-category">
            <a href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/"> 编程语言 </a>
            </div>
          <span class="more-meta"> 约 1426 字 </span>
          <span class="more-meta"> 预计阅读 3 分钟 </span>
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li><a href="#数据类">数据类</a></li>
    <li><a href="#函数默认值">函数默认值</a></li>
    <li><a href="#列表过滤">列表过滤</a></li>
    <li><a href="#字符串插值">字符串插值</a></li>
    <li><a href="#对象检查">对象检查</a></li>
    <li><a href="#遍历映射列表">遍历映射/列表</a></li>
    <li><a href="#使用范围">使用范围</a></li>
    <li><a href="#只读映射列表">只读映射/列表</a></li>
    <li><a href="#映射访问">映射访问</a></li>
    <li><a href="#懒值lazy">懒值(Lazy)</a></li>
    <li><a href="#扩展">扩展</a></li>
    <li><a href="#单例">单例</a></li>
    <li><a href="#null值检查">null值检查</a></li>
    <li><a href="#when表达式作为返回值">when表达式作为返回值</a></li>
    <li><a href="#trycatch">try/catch</a></li>
    <li><a href="#if">if</a></li>
    <li><a href="#使用with调用多个方法">使用with调用多个方法</a></li>
    <li><a href="#java-7的try-with-resources语句">Java 7的try-with-resources语句</a></li>
    <li><a href="#泛型">泛型</a></li>
    <li><a href="#可空布尔类型使用">可空布尔类型使用</a></li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <h2 id="数据类">数据类</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">data</span> <span class="k">class</span> <span class="nc">Customer</span><span class="p">(</span><span class="k">val</span> <span class="py">name</span><span class="p">:</span> <span class="n">String</span><span class="p">,</span> <span class="k">val</span> <span class="py">email</span><span class="p">:</span> <span class="n">String</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>Customer提供了以下方法：</p>
<ul>
<li>getters，如果成员变量使用var定义那么还默认提供setters</li>
<li>equals()</li>
<li>hashCode()</li>
<li>toString()</li>
<li>copy()</li>
<li>component1(), component2() &hellip;</li>
</ul>
<p>这跟Scala的<code>case class</code>基本上差不多，一般在做数据交互/传输时用</p>
<h2 id="函数默认值">函数默认值</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">fun</span> <span class="nf">foo</span><span class="p">(</span><span class="n">a</span><span class="p">:</span> <span class="n">Int</span> <span class="p">=</span> <span class="m">0</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="n">String</span> <span class="p">=</span> <span class="s2">&#34;&#34;</span><span class="p">)</span> <span class="p">{</span> <span class="o">..</span><span class="p">.</span> <span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="列表过滤">列表过滤</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">positives</span> <span class="p">=</span> <span class="n">list</span><span class="p">.</span><span class="n">filter</span> <span class="p">{</span> <span class="n">x</span> <span class="o">-&gt;</span> <span class="n">x</span> <span class="p">&gt;</span> <span class="m">0</span> <span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>或者更短一点</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">positives</span> <span class="p">=</span> <span class="n">list</span><span class="p">.</span><span class="n">filter</span> <span class="p">{</span> <span class="k">it</span> <span class="p">&gt;</span> <span class="m">0</span> <span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>默认使用it来接收单个的参数</p>
<h2 id="字符串插值">字符串插值</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="n">println</span><span class="p">(</span><span class="s2">&#34;Name </span><span class="si">$name</span><span class="s2">&#34;</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="对象检查">对象检查</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">when</span> <span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">is</span> <span class="n">Foo</span> <span class="o">-&gt;</span> <span class="o">..</span><span class="p">.</span>
    <span class="k">is</span> <span class="n">Bar</span> <span class="o">-&gt;</span> <span class="o">..</span><span class="p">.</span>
    <span class="k">else</span>   <span class="o">-&gt;</span> <span class="o">..</span><span class="p">.</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>非常精简，再也不要写Java那个烦人的<code>instanceof</code></p>
<h2 id="遍历映射列表">遍历映射/列表</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">for</span> <span class="p">((</span><span class="n">k</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span> <span class="k">in</span> <span class="n">map</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">println</span><span class="p">(</span><span class="s2">&#34;</span><span class="si">$k</span><span class="s2"> -&gt; </span><span class="si">$v</span><span class="s2">&#34;</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>k, v分别是map的key和value，是list的index和value</p>
<h2 id="使用范围">使用范围</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="k">in</span> <span class="m">1.</span><span class="p">.</span><span class="m">100</span><span class="p">)</span> <span class="p">{</span> <span class="o">..</span><span class="p">.</span> <span class="p">}</span>  <span class="c1">// closed range: includes 100
</span><span class="c1"></span><span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="k">in</span> <span class="m">1</span> <span class="n">until</span> <span class="m">100</span><span class="p">)</span> <span class="p">{</span> <span class="o">..</span><span class="p">.</span> <span class="p">}</span> <span class="c1">// half-open range: does not include 100
</span><span class="c1"></span><span class="k">for</span> <span class="p">(</span><span class="n">x</span> <span class="k">in</span> <span class="m">2.</span><span class="p">.</span><span class="m">10</span> <span class="n">step</span> <span class="m">2</span><span class="p">)</span> <span class="p">{</span> <span class="o">..</span><span class="p">.</span> <span class="p">}</span>
<span class="k">for</span> <span class="p">(</span><span class="n">x</span> <span class="k">in</span> <span class="m">10</span> <span class="n">downTo</span> <span class="m">1</span><span class="p">)</span> <span class="p">{</span> <span class="o">..</span><span class="p">.</span> <span class="p">}</span>
<span class="k">if</span> <span class="p">(</span><span class="n">x</span> <span class="k">in</span> <span class="m">1.</span><span class="p">.</span><span class="m">10</span><span class="p">)</span> <span class="p">{</span> <span class="o">..</span><span class="p">.</span> <span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="只读映射列表">只读映射/列表</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">list</span> <span class="p">=</span> <span class="n">listOf</span><span class="p">(</span><span class="s2">&#34;a&#34;</span><span class="p">,</span> <span class="s2">&#34;b&#34;</span><span class="p">,</span> <span class="s2">&#34;c&#34;</span><span class="p">)</span>
<span class="k">val</span> <span class="py">map</span> <span class="p">=</span> <span class="n">mapOf</span><span class="p">(</span><span class="s2">&#34;a&#34;</span> <span class="n">to</span> <span class="m">1</span><span class="p">,</span> <span class="s2">&#34;b&#34;</span> <span class="n">to</span> <span class="m">2</span><span class="p">,</span> <span class="s2">&#34;c&#34;</span> <span class="n">to</span> <span class="m">3</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>如果是集合是不是还有<code>setOf</code>，命名的统一性也是Kotlin的一个亮点，如果你使用过php的话，感觉函数总是记不住。</p>
<h2 id="映射访问">映射访问</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="n">println</span><span class="p">(</span><span class="n">map</span><span class="p">[</span><span class="s2">&#34;key&#34;</span><span class="p">])</span>
<span class="n">map</span><span class="p">[</span><span class="s2">&#34;key&#34;</span><span class="p">]</span> <span class="p">=</span> <span class="n">value</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="懒值lazy">懒值(Lazy)</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">p</span><span class="p">:</span> <span class="n">String</span> <span class="k">by</span> <span class="n">lazy</span> <span class="p">{</span>
    <span class="c1">// compute the string
</span><span class="c1"></span><span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>这段代码在定义的时候是不会执行变量的值的，只有在使用这个变量的时候才会求值</p>
<h2 id="扩展">扩展</h2>
<p>这是Kotlin一个非常强大的功能，可以对原来已经存在的类添加一系列的新方法，扩展别人的包非常方便</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">fun</span> <span class="nf">String</span><span class="p">.</span><span class="n">spaceToCamelCase</span><span class="p">()</span> <span class="p">{</span> <span class="o">..</span><span class="p">.</span> <span class="p">}</span>

<span class="s2">&#34;Convert this to camelcase&#34;</span><span class="p">.</span><span class="n">spaceToCamelCase</span><span class="p">()</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="单例">单例</h2>
<p>做Java是不是会经常被问单例模式是怎么实现的，Kotlin直接使用object来定义，直白得不要不要的，这和Scala也是一样的</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">object</span> <span class="nc">Resource</span> <span class="p">{</span>
    <span class="k">val</span> <span class="py">name</span> <span class="p">=</span> <span class="s2">&#34;Name&#34;</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="null值检查">null值检查</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">files</span> <span class="p">=</span> <span class="n">File</span><span class="p">(</span><span class="s2">&#34;Test&#34;</span><span class="p">).</span><span class="n">listFiles</span><span class="p">()</span>
<span class="n">println</span><span class="p">(</span><span class="n">files</span><span class="o">?.</span><span class="n">size</span><span class="p">)</span>
<span class="n">println</span><span class="p">(</span><span class="n">files</span><span class="o">?.</span><span class="n">size</span> <span class="o">?:</span> <span class="s2">&#34;empty&#34;</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>相比Java的<code>if (files != null)</code>优雅太多了。files如果是空值，新手写代码如果不做Null检查，就会碰到最常见的NullException。Kotlin使用问号来检查，并且null值会一值传递到最后。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">data</span> <span class="p">=</span> <span class="o">..</span><span class="p">.</span>
<span class="k">val</span> <span class="py">email</span> <span class="p">=</span> <span class="k">data</span><span class="p">[</span><span class="s2">&#34;email&#34;</span><span class="p">]</span> <span class="o">?:</span> <span class="k">throw</span> <span class="n">IllegalStateException</span><span class="p">(</span><span class="s2">&#34;Email is missing!&#34;</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p>Kotlin使用<code>?:</code>也是非常的简洁，如果<code>data[&quot;email&quot;]</code>有值，直接使用，如果没有就抛出异常。如果想只有在有值的情况下</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">data</span> <span class="p">=</span> <span class="o">..</span><span class="p">.</span>

<span class="k">data</span><span class="o">?.</span><span class="n">let</span> <span class="p">{</span>
    <span class="o">..</span><span class="p">.</span> <span class="c1">// execute this block if not null
</span><span class="c1"></span><span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>映射空值检查</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">data</span> <span class="p">=</span> <span class="o">..</span><span class="p">.</span>

<span class="k">val</span> <span class="py">mapped</span> <span class="p">=</span> <span class="k">data</span><span class="o">?.</span><span class="n">let</span> <span class="p">{</span> <span class="n">transformData</span><span class="p">(</span><span class="k">it</span><span class="p">)</span> <span class="p">}</span> <span class="o">?:</span> <span class="n">defaultValueIfDataIsNull</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="when表达式作为返回值">when表达式作为返回值</h2>
<p>Kotlin是基于表达式，而不是基于语句的。也就是说任何的语言结构都是有返回值的，这也是和Scala是一样的。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">fun</span> <span class="nf">transform</span><span class="p">(</span><span class="n">color</span><span class="p">:</span> <span class="n">String</span><span class="p">):</span> <span class="n">Int</span> <span class="p">{</span>
    <span class="k">return</span> <span class="k">when</span> <span class="p">(</span><span class="n">color</span><span class="p">)</span> <span class="p">{</span>
        <span class="s2">&#34;Red&#34;</span> <span class="o">-&gt;</span> <span class="m">0</span>
        <span class="s2">&#34;Green&#34;</span> <span class="o">-&gt;</span> <span class="m">1</span>
        <span class="s2">&#34;Blue&#34;</span> <span class="o">-&gt;</span> <span class="m">2</span>
        <span class="k">else</span> <span class="o">-&gt;</span> <span class="k">throw</span> <span class="n">IllegalArgumentException</span><span class="p">(</span><span class="s2">&#34;Invalid color param value&#34;</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>这里<code>when</code>是一个表达式，表达式是有值的，如果color是Green，那么这个<code>when</code>的值就是2</p>
<h2 id="trycatch">try/catch</h2>
<p>同样try/catch也是有值的</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">fun</span> <span class="nf">test</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">val</span> <span class="py">result</span> <span class="p">=</span> <span class="k">try</span> <span class="p">{</span>
        <span class="n">count</span><span class="p">()</span>
    <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="n">e</span><span class="p">:</span> <span class="n">ArithmeticException</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="n">IllegalStateException</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
    <span class="p">}</span>

    <span class="c1">// Working with result
</span><span class="c1"></span><span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="if">if</h2>
<p>if也是表达式，也是有值的</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">fun</span> <span class="nf">foo</span><span class="p">(</span><span class="k">param</span><span class="p">:</span> <span class="n">Int</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">val</span> <span class="py">result</span> <span class="p">=</span> <span class="k">if</span> <span class="p">(</span><span class="k">param</span> <span class="o">==</span> <span class="m">1</span><span class="p">)</span> <span class="p">{</span>
        <span class="s2">&#34;one&#34;</span>
    <span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="k">param</span> <span class="o">==</span> <span class="m">2</span><span class="p">)</span> <span class="p">{</span>
        <span class="s2">&#34;two&#34;</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="s2">&#34;three&#34;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>如果上面最后那个else没有写的话，编译是通不过的，如果<code>if</code>作为一个表达式，那么必须覆盖所有的情况。</p>
<h2 id="使用with调用多个方法">使用with调用多个方法</h2>
<p>这个特性也比较酷，结构跟python的差不多：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">class</span> <span class="nc">Turtle</span> <span class="p">{</span>
    <span class="k">fun</span> <span class="nf">penDown</span><span class="p">()</span>
    <span class="k">fun</span> <span class="nf">penUp</span><span class="p">()</span>
    <span class="k">fun</span> <span class="nf">turn</span><span class="p">(</span><span class="n">degrees</span><span class="p">:</span> <span class="n">Double</span><span class="p">)</span>
    <span class="k">fun</span> <span class="nf">forward</span><span class="p">(</span><span class="n">pixels</span><span class="p">:</span> <span class="n">Double</span><span class="p">)</span>
<span class="p">}</span>

<span class="k">val</span> <span class="py">myTurtle</span> <span class="p">=</span> <span class="n">Turtle</span><span class="p">()</span>
<span class="n">with</span><span class="p">(</span><span class="n">myTurtle</span><span class="p">)</span> <span class="p">{</span> <span class="c1">//draw a 100 pix square
</span><span class="c1"></span>    <span class="n">penDown</span><span class="p">()</span>
    <span class="k">for</span><span class="p">(</span><span class="n">i</span> <span class="k">in</span> <span class="m">1.</span><span class="p">.</span><span class="m">4</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">forward</span><span class="p">(</span><span class="m">100.0</span><span class="p">)</span>
        <span class="n">turn</span><span class="p">(</span><span class="m">90.0</span><span class="p">)</span>
    <span class="p">}</span>
    <span class="n">penUp</span><span class="p">()</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="java-7的try-with-resources语句">Java 7的try-with-resources语句</h2>
<p>在Java 7的写法如下</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Java" data-lang="Java"><span class="k">try</span> <span class="o">(</span><span class="n">BufferedReader</span> <span class="n">br</span> <span class="o">=</span> <span class="k">new</span> <span class="n">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="n">FileReader</span><span class="o">(</span><span class="n">path</span><span class="o">)))</span> <span class="o">{</span>
    <span class="k">return</span> <span class="n">br</span><span class="o">.</span><span class="na">readLine</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></td></tr></table>
</div>
</div><p>在Kotlin写法更加直观</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">stream</span> <span class="p">=</span> <span class="n">Files</span><span class="p">.</span><span class="n">newInputStream</span><span class="p">(</span><span class="n">Paths</span><span class="p">.</span><span class="k">get</span><span class="p">(</span><span class="s2">&#34;/some/file.txt&#34;</span><span class="p">))</span>
<span class="n">stream</span><span class="p">.</span><span class="n">buffered</span><span class="p">().</span><span class="n">reader</span><span class="p">().</span><span class="n">use</span> <span class="p">{</span> <span class="n">reader</span> <span class="o">-&gt;</span>
    <span class="n">println</span><span class="p">(</span><span class="n">reader</span><span class="p">.</span><span class="n">readText</span><span class="p">())</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="泛型">泛型</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="c1">//  public final class Gson {
</span><span class="c1">//     ...
</span><span class="c1">//     public &lt;T&gt; T fromJson(JsonElement json, Class&lt;T&gt; classOfT) throws JsonSyntaxException {
</span><span class="c1">//     ...
</span><span class="c1"></span>
<span class="k">inline</span> <span class="k">fun</span> <span class="p">&lt;</span><span class="k">reified</span> <span class="nc">T</span><span class="p">:</span> <span class="nc">Any</span><span class="p">&gt;</span> <span class="nf">Gson</span><span class="p">.</span><span class="n">fromJson</span><span class="p">(</span><span class="n">json</span><span class="p">):</span> <span class="n">T</span> <span class="p">=</span> <span class="k">this</span><span class="p">.</span><span class="n">fromJson</span><span class="p">(</span><span class="n">json</span><span class="p">,</span> <span class="n">T</span><span class="o">::</span><span class="k">class</span><span class="p">.</span><span class="n">java</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="可空布尔类型使用">可空布尔类型使用</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">b</span><span class="p">:</span> <span class="n">Boolean</span><span class="p">?</span> <span class="p">=</span> <span class="o">..</span><span class="p">.</span>
<span class="k">if</span> <span class="p">(</span><span class="n">b</span> <span class="o">==</span> <span class="k">true</span><span class="p">)</span> <span class="p">{</span>
    <span class="o">..</span><span class="p">.</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// `b` is false or null
</span><span class="c1"></span><span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div>
    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">Kevin Jiang</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2017-06-13
        
    </span>
  </p>
  
  <p class="copyright-item">
    <span class="item-title">许可协议</span>
    <span class="item-content"><a rel="license noopener" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank">CC BY-NC-ND 4.0</a></span>
  </p>
</div>
<div class="post-reward">
  <input type="checkbox" name="reward" id="reward" hidden />
  <label class="reward-button" for="reward">赞赏支持</label>
  <div class="qr-code">
    
    <label class="qr-code-image" for="reward">
        <img class="image" src="/img/wechat_pay_1242x1242.jpg">
        <span>微信打赏</span>
      </label>
    <label class="qr-code-image" for="reward">
        <img class="image" src="/img/alipay_600x600.jpg">
        <span>支付宝打赏</span>
      </label>
  </div>
</div><footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/kotlin/">Kotlin</a>
          <a href="/tags/kotlin%E6%95%99%E7%A8%8B/">Kotlin教程</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/kotlin/%E6%88%91%E6%9D%A5%E5%AD%A6kotlin-%E8%B5%B7%E6%AD%A5%E4%B9%8B%E4%BB%A3%E7%A0%81%E8%A7%84%E8%8C%83/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">我来学Kotlin-起步之代码规范</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/%E6%88%91%E7%9A%84%E5%BF%85%E5%A4%87%E5%B7%A5%E5%85%B7%E7%AE%B1/">
            <span class="next-text nav-default">我的必备工具箱</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:wenlin1988@126.com" class="iconfont icon-email" title="email"></a>
      <a href="https://www.linkedin.com/in/%E6%96%87%E6%9E%97-%E8%92%8B-0a3204126/" class="iconfont icon-linkedin" title="linkedin"></a>
      <a href="https://github.com/kevindragon" class="iconfont icon-github" title="github"></a>
  <a href="http://kevinjiang.info/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>

<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 -
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  

  <span class="copyright-year">
    &copy;
    2015 -
    2023<span class="heart"><i class="iconfont icon-heart"></i></span><span>Kevin Jiang</span>
    <a href="https://beian.miit.gov.cn/" target="_blank">湘ICP备2022022745号</a>
  </span>
</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.c99b103c33d1539acf3025e1913697534542c4a5aa5af0ccc20475ed2863603b.js"></script>
  <script type="text/javascript">
    window.MathJax = {
      tex: {
        inlineMath: [['$','$'], ['\\(','\\)']],
        tags: 'ams',
        }
    };
  </script>
  <script type="text/javascript" async src="/lib/mathjax/es5/tex-mml-chtml.js"></script>

<script id="baidu_analytics">
  var _hmt = _hmt || [];
  (function() {
    if (window.location.hostname === 'localhost') return;
    var hm = document.createElement("script"); hm.async = true;
    hm.src = "https://hm.baidu.com/hm.js?b73ff6d4afc4af9e582d8a5dc068bab9";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
</script>






</body>
</html>
